import { createRouter } from "../createRouterMap";
function runQueue(queue, iterator, cb) {
  // 异步执行,
  function step(index) {
    // 全部执行完, 说明执行完了 走callback
    if (index >= queue.length) return cb();
    let hook = queue[index];
    iterator(hook, () => {
      step(index + 1);
    });
  }
  step(0);
}
// 公共方法
class history {
  constructor(router) {
    // console.log(router, "这是是一个集成");
    this.router = router;
    this.current = createRouter(null, { path: "/" });
  }
  push(to) {
    this.transitionsTo(to, () => {
      window.location.hash = to;
    });
  }
  listen(cb) {
    this.cb = cb;
  }
  transitionsTo(location, cb) {
    // console.log(location);
    // location是最新的地址, 根据这个地址进行渲染地址
    let router = this.router.match.match(location);

    this.current = createRouter(router, { path: location });

    // 获取全局守卫的列队
    let queue = [].concat(this.router.beforeHooks);
    // 定义方法, 列队执行
    const iterator = (hook, next) => {
      // 当前的这个组件的
      hook(this.current, router, () => {
        next();
      });
    };
    runQueue(queue, iterator, () => {
      this.cb && this.cb(this.current);
      // console.log(this.current);
      cb && cb();
    });
    // console.log(queue);
  }
}

export { history };
